//
//  YZChatMainVC.m
//  VET
//
//  Created by lixiaoyi on 2018/7/11.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZChatMainVC.h"
#import "TapScrollView.h"
#import "ChatHeader.h"
#import "YZSearchFriendVC.h"
#import "YZAddFriendVC.h"
#import "YZMessageListModel.h"
#import "YZMessageConst.h"
#import "UIView+YZBadge.h"
#import "YZFriendVM.h"
#import "YZMessageListCell.h"
#import "YZDBManager.h"
#import "YZUser.h"
#import "YZSystemMessageVC.h"
#import "YZChatVC.h"
#import "YZChatPeer.h"
#import "RefreshTableView.h"
#import "YZFriendModel.h"
#import "YZFriendListCell1.h"
#import "YZFriendListCell2.h"
#import "YZNewFriend.h"

#define kChatMainVCItem1  @"消息"
#define kChatMainVCItem2  @"好友"

static NSString *flagCell = @"YZMessageListCell";
static NSString *flagCell1 = @"YZFriendListCell1";
static NSString *flagCell2 = @"YZFriendListCell2";

// 每页显示条数
static NSUInteger perPageNumber = 20;

@interface YZChatMainVC ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CustomRefreshDelegate>
@property (nonatomic, strong) TapScrollView *tapScrollView;
@property (nonatomic, strong) UINavigationBar *navBar;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIButton *rightBtn;

/* MessageList */
@property (nonatomic, strong) UITableView *messageList;
@property (nonatomic, strong) NSMutableArray *listData;
@property (nonatomic, strong) YZFriendVM *friendVM;

/* FriendList */
@property (nonatomic, strong) RefreshTableView *friendList;
@property (nonatomic, strong) NSMutableArray *friendData;
@property (nonatomic, strong) NSMutableArray *sectionTitleArr;
@property (nonatomic, strong) YZFriendModel *lastestModel;
@property (nonatomic, strong) NSMutableArray *lastestModelArr;
@property (nonatomic) BOOL haveLatestFriend;
@property (nonatomic) PullDirection pullDirection;
@property (nonatomic) NSUInteger pageNo;
@property (nonatomic) NSUInteger lastPageNo;

@end

@implementation YZChatMainVC

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self makeViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 隐藏导航
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    // 查询消息记录
    self.listData = [[YZDBManager sharedManage] queryDataFromTable:kChatMessageListTable andCondition:[NSString stringWithFormat:@"receiver = '%@' or sender = '%@'",[YZUser sharedInstance].uid,[YZUser sharedInstance].uid]];
    
    [self.messageList reloadData];
    
    // 接收更新tab小红点的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTabDot:) name:ShowTabRedDotNotification object:nil];
    
    // 接收消息列表通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMessageListTable:) name:RefreshMessaegListNotification object:nil];
    
    
    // 先删除所有好友数据
    if ([self.friendData count]>0) {
        [self.friendData removeAllObjects];
    }
    
    // 查询最近一条好友申请记录
    NSString *condition = [NSString stringWithFormat:@"auditStatus = %d",2];
    NSArray *arr = [[YZDBManager sharedManage] queryDataFromTable:kNewFriendTable andCondition:condition];
    if ([arr count] > 0) {
        self.haveLatestFriend = YES;
        self.lastestModel = arr[0];
        self.lastestModel.showRedDot = YES;
    }
    
    if (!self.haveLatestFriend) {
        YZFriendModel *model = [YZFriendModel new];
        model.iconName = @"";
        model.name = @"";
        model.info = @"";
        model.targetId = @"";
        
        NSDictionary *sec0 = @{@"key" : @[model]};
        [self.friendData addObject:sec0];
    } else {
        if (self.lastestModelArr) {
            NSDictionary *tempDic = @{@"key" : @[self.lastestModel]};
            [self.friendData insertObject:tempDic atIndex:0];
        }
    }
    
    
    // 自动下拉刷新一次
    [self performSelector:@selector(pullDownDataWithType:) withObject:0 afterDelay:0.1];
    
    // 接收刷新好友列表通知(本页面)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshFriendList:) name:RefreshFriendListNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 打开导航
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    // fix键盘不显示
    self.navigationController.navigationBar.translucent = YES;
}

#pragma mark - init
- (void)makeViews {
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建导航Bar
    self.navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,44)];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        self.navBar.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width,44);
    }
    [self.navBar setBackgroundColor:[UIColor whiteColor]];
    [self.navBar addSubview:self.tapScrollView];
    [self.navBar addSubview:self.rightBtn];
    
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.mainScrollView];
    
    [self.mainScrollView addSubview:self.messageList];
    
    [self.mainScrollView addSubview:self.friendList];
    
    [self registerCell];
    // 设置是否有最新申请
    _haveLatestFriend = NO;
    
    // 设置从第一页开始
    self.pageNo = 0;
    
    // 设置总页码
    self.lastPageNo = 0;
    
    // 设置初始下拉状态
    self.pullDirection = PullDirectionDown;
}

#pragma mark - lazyload
- (UIScrollView *)mainScrollView {
    if (!_mainScrollView) {
        CGFloat width = self.view.bounds.size.width;
        CGFloat height = self.view.bounds.size.height;
        CGRect frame = CGRectMake(0, 64, width, height);
        _mainScrollView = [[UIScrollView alloc] initWithFrame:frame];
        _mainScrollView.scrollEnabled = YES;
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.contentSize = CGSizeMake(width * 2, height);
        _mainScrollView.delegate = self;
    }
    
    return _mainScrollView;
}

- (TapScrollView *)tapScrollView {
    if (!_tapScrollView) {
        _tapScrollView = [[TapScrollView alloc] initWithFrame:CGRectMake(100, 0, self.view.bounds.size.width - 200, 44) buttonsArr:@[kChatMainVCItem1,kChatMainVCItem2]];
        
        __weak typeof(self) weakSelf = self;
        self.tapScrollView.tapScrollViewBlock = ^(NSUInteger index) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (1000 == index) {
                [UIView animateWithDuration:0.1 animations:^{
                    [strongSelf.mainScrollView scrollRectToVisible:CGRectMake(0, 0, strongSelf.view.frame.size.width, strongSelf.view.frame.size.height) animated:YES];
                }];
            } else if (1001 == index) {
                [UIView animateWithDuration:0.1 animations:^{
                    [strongSelf.mainScrollView scrollRectToVisible:CGRectMake(strongSelf.view.frame.size.width, 0, strongSelf.view.frame.size.width, strongSelf.view.frame.size.height) animated:YES];
                }];
            }
        };
    }
    
    return _tapScrollView;
}

- (UIButton *)rightBtn {
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightBtn setTitle:@"" forState:UIControlStateNormal];
        _rightBtn.frame = CGRectMake(kWidth - 60, 0, 60, 40);
        [_rightBtn setImage:[UIImage imageNamed:@"ico_addfriend"]
                  forState:UIControlStateNormal];
        
        @weakify(self)
        [[_rightBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            
            YZSearchFriendVC *serachFriend = [[YZSearchFriendVC alloc] init];
            [self.navigationController pushViewController:serachFriend animated:YES];
        }];
    }
   
    return _rightBtn;
}

- (UITableView *)messageList {
    if (!_messageList) {
        CGRect tableF = CGRectMake(0, -30, kWidth, kHeight);
        _messageList = [[UITableView alloc] initWithFrame:tableF style:UITableViewStyleGrouped];
        _messageList.dataSource = self;
        _messageList.delegate = self;
        _messageList.tag = 2000;
        [_messageList registerClass:[YZMessageListCell class] forCellReuseIdentifier:flagCell];
    }
    
    return _messageList;
}

- (NSMutableArray *)listData {
    if (!_listData) {
        _listData = [NSMutableArray array];
    }
    
    return _listData;
}

- (YZFriendVM *)friendVM {
    if (!_friendVM) {
        _friendVM = [YZFriendVM new];
    }
    
    return _friendVM;
}

/* FriendList */
- (UITableView *)friendList {
    if (!_friendList) {
        CGRect friendListFrame = CGRectMake(kWidth, -30, kWidth, kHeight);
        _friendList = [[RefreshTableView alloc] initWithDelegate:self andStyle:UITableViewStyleGrouped andTradeType:0];
        _friendList.frame = friendListFrame;
        _friendList.tag = 2001;
        _friendList.refreshDeleage = self;
        _friendList.delegate = self;
        _friendList.dataSource = self;
    }
    
    return _friendList;
}

- (NSMutableArray *)sectionTitleArr {
    if (!_sectionTitleArr) {
        _sectionTitleArr = [NSMutableArray array];
        [_sectionTitleArr addObject:@""];
        [_sectionTitleArr addObject:@"所有好友"];
    }
    
    return _sectionTitleArr;
}

- (NSMutableArray *)friendData {
    if (!_friendData) {
        _friendData = [NSMutableArray array];
    }
    
    return _friendData;
}

- (NSMutableArray *)lastestModelArr {
    if (!_lastestModelArr) {
        _lastestModelArr = [NSMutableArray array];
    }
    
    return _lastestModelArr;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (2000 == tableView.tag) {
        return 1;
    } else if (2001 == tableView.tag) {
        return [self.friendData count];
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (2000 == tableView.tag) {
        return [self.listData count];
    } else if (2001 == tableView.tag) {
        return [self.friendData[section][@"key"] count];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger sec = indexPath.section;
    NSUInteger row = indexPath.row;
    if (2000 == tableView.tag) {
        YZMessageListCell *msgListCell = [tableView dequeueReusableCellWithIdentifier:flagCell];
        [msgListCell setModel:self.listData[row]];
        
        return msgListCell;
    } else if (2001 == tableView.tag) {
        
        if (0 == sec) {
            
            YZFriendListCell2 *cell2 =  [tableView dequeueReusableCellWithIdentifier:flagCell2];
            cell2.model = self.friendData[sec][@"key"][row];
            
            return cell2;
        } else {
            
            YZFriendListCell1 *cell1 = [tableView dequeueReusableCellWithIdentifier:flagCell1];
            cell1.model = self.friendData[sec][@"key"][row];
            
            return cell1;
        }
    }
    
    
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (2000 == tableView.tag) {
        return 70;
    } else if (2001 == tableView.tag) {
        return 54;
    }
    
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (2001 == tableView.tag) {
        return self.sectionTitleArr[section];
    } else {
        return @"";
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger sec = indexPath.section;
    NSUInteger row = indexPath.row;
    if (2000 == tableView.tag) {
        YZMessageListModel *model = self.listData[indexPath.row];
        if ([model.messType isEqualToString:@"system"]) {
            // 系统消息
            YZSystemMessageVC *sysVC = [[YZSystemMessageVC alloc] init];
            [self.navigationController pushViewController:sysVC animated:YES];
        } else {
            YZChatVC *vc = [YZChatVC new];
            [YZChatPeer shared].sender = [YZUser sharedInstance].uid;
            [YZChatPeer shared].receiver = model.showUserId;
            [YZChatPeer shared].senderAvatar = [YZUser sharedInstance].avatar;
            [YZChatPeer shared].receiverAvatar = model.imageName;
            vc.hidesBottomBarWhenPushed = YES;
            vc.view.backgroundColor = [UIColor whiteColor];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        // 隐藏小红点
        YZMessageListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell hideRedHot];
        
        // 更新数据库小红点数量为0
        [self updateMessageListRedDotNumber:model];
    } else if (2001 == tableView.tag) {
        
        if (0 == sec) {
            if (_haveLatestFriend) {
                YZNewFriend *newFriend = [[YZNewFriend alloc] init];
                newFriend.latestFriendArr = self.lastestModelArr;
                newFriend.dealBlock = ^(BOOL processed) {
                    if (processed) {
                        self.haveLatestFriend = NO;
                        // 去掉小红点
                        YZFriendListCell2 *cell2 = [tableView cellForRowAtIndexPath:indexPath];
                        [cell2 hideRedHot];
                    }
                };
                
                [self.navigationController pushViewController:newFriend animated:YES];
                
            } else {
                YZNewFriend *newFriend = [[YZNewFriend alloc] init];
                [self.navigationController pushViewController:newFriend animated:YES];
            }
        } else {
            YZChatVC *vc = [YZChatVC new];
            [YZChatPeer shared].sender = [YZUser sharedInstance].uid;
            YZFriendModel *model = [self.friendData objectAtIndex:sec][@"key"][row];
            [YZChatPeer shared].receiver = model.targetId;
            [YZChatPeer shared].senderAvatar = [YZUser sharedInstance].avatar;
            [YZChatPeer shared].receiverAvatar = model.iconName;
            vc.hidesBottomBarWhenPushed = YES;
            vc.view.backgroundColor = [UIColor whiteColor];
            [self.navigationController pushViewController:vc animated:YES];
            
            //        NSUInteger row = indexPath.row;
            //        YZFriendModel *model = [self.friendData[1][@"key"] objectAtIndex:row];
            //        NSString *targetId = model.targetId;
            //        [self friendDataDelete:targetId];
        }
        
    }
}

#pragma mark - refreshDelegate
// 下拉
- (void)pullDownDataWithType:(NSUInteger)type{
    self.pullDirection = 1;
    self.pageNo = 0;
    [self friendDataRequest:0 type:PullDirectionDown];
}

// 上拉
- (BOOL)pullUpDataWithType:(NSUInteger)type{
    self.pullDirection = 0;
    self.pageNo += 1;
    if (self.pageNo <= self.lastPageNo) {
        [self friendDataRequest:self.pageNo type:PullDirectionUp];
    } else {
        [SVProgressHUD showInfoWithStatus:@"数据已全部加载完毕"];
    }
    
    return YES;
}

#pragma mark - network
// 请求好友列表
- (void)friendDataRequest:(NSUInteger)pageNo
                     type:(PullDirection)pullType{
    @weakify(self)
    [[self.friendVM getFriends:pageNo size:perPageNumber] subscribeNext:^(id  _Nullable x) {
        NSLog(@"接口返回朋友列表------>%@",x);
        @try {
            NSArray *list = x[@"list"];
            NSArray *modelList = [YZFriendModel mj_objectArrayWithKeyValuesArray:list];
            if ([modelList count] > 0 && pullType == PullDirectionDown) {
                if ([self.friendData count] == 1) {
                    [self.friendData insertObject:@{@"key":modelList} atIndex:1];
                } else {
                    [self.friendData replaceObjectAtIndex:1 withObject:@{@"key":modelList}];
                }
            }
            
            if (!kObjectIsEmpty(x[@"lastPage"])) {
                self.lastPageNo = [x[@"lastPage"] integerValue];
            }
        } @catch(NSException *exception) {
            
        }
    } completed:^{
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.friendList reloadData];
        });
    }];
}

#pragma mark - 删除好友
- (void)friendDataDelete:(NSString *)targetId {
    @weakify(self)
    [[self.friendVM deleFriend:targetId] subscribeNext:^(id  _Nullable x) {
        NSLog(@"删除朋友------>%@",x);
        @try {
            
        } @catch(NSException *exception) {
            
        }
    } completed:^{
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.friendList reloadData];
        });
    }];
}

#pragma mark - 查询用户信息(更新消息列表)
- (void)queryUserInfo:(YZMessageListModel *)model {
    @weakify(self)
    [[self.friendVM queryUserInfo:model.showUserId] subscribeNext:^(id  _Nullable x) {
        NSLog(@"查询用户信息------>%@",x);
        
        @try {
            // 判断是否存在
            BOOL isExist = NO;
            NSUInteger count = self.listData.count;
            if (count > 0)  {
                for (int idx = 0; idx <= count - 1; idx++) {
                    YZMessageListModel *tempModel = self.listData[idx];
                    if ([model.showUserId isEqualToString:tempModel.showUserId]
                        ) {
                        [self.listData removeObject:tempModel];
                        isExist = YES;
                        break;
                    }
                }
            }
            
            // 更新头像和昵称
            model.imageName =  x[@"avatar"] ? : @"";
            model.name =  x[@"nickname"] ? : @"";
            
            [self.listData addObject:model];
            
            if (isExist) {
                // 更新消息列表
                [self updateAcceptMessageList:model];
            }
            else {
                // 保存消息列表
                [self saveAcceptMessageList:model];
            }
            
            
            // 按倒序排列
            [self.listData sortUsingComparator:^NSComparisonResult(YZMessageListModel*  _Nonnull obj1, YZMessageListModel *  _Nonnull obj2) {
                NSNumber *objNum1 = [NSNumber numberWithLongLong:obj1.time];
                NSNumber *objNum2 = [NSNumber numberWithLongLong:obj2.time];
                return [objNum2 compare:objNum1];
            }];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新
                [self.messageList reloadData];
                
                // 滑到最后一行
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.listData.count - 1 inSection:0];
                [self.messageList scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            });
        } @catch(NSException *exception) {
            
        }
    } completed:^{
        @strongify(self)
    }];
}

#pragma mark - 查询用户信息(更新好友列表)
- (void)queryUserInfo:(NSString *)targetId controller:(YZChatMainVC *)vc {
    @weakify(self)
    [[self.friendVM queryUserInfo:targetId] subscribeNext:^(id  _Nullable x) {
        NSLog(@"查询用户信息------>%@",x);
        @try {
            NSDictionary *tempDic = nil;
            if ([self.friendData count] == 0) {
                tempDic = [NSDictionary dictionary];
            } else {
                tempDic = self.friendData[0];
            }
            
            if (self.friendList) {}
            
            self.lastestModel.iconName = x[@"avatar"] ? : @"";
            self.lastestModel.name = x[@"nickname"] ? : @"";
            if (tempDic[@"key"]) {
                tempDic = nil;
                tempDic = @{@"key" : @[self.lastestModel]};
            } else {
                tempDic = @{@"key" : @[self.lastestModel]};
            }
            self.friendData[0] = tempDic;
            
            
            // 把新朋友插入或更新到数据库
            NSUInteger lastFriendCount = [vc.lastestModelArr count];
            if (lastFriendCount > 0) {
                for (int index = 0; index < lastFriendCount; index++) {
                    NSArray *arr = nil;
                    YZFriendModel *tempModel = vc.lastestModelArr[index];
                    NSString *condition = [NSString stringWithFormat:@"targetId = %@",tempModel.targetId];
                    arr = [[YZDBManager sharedManage] queryDataFromTable:kNewFriendTable andCondition:condition];
                    if (arr.count == 0) {
                        // 插入
                        [self insertNewFriend:tempModel];
                    } else {
                        // 更新
                        NSString *setStr = [NSString stringWithFormat:@"iconUrl = '%@',name = '%@',auditStatus = '%lu'",tempModel.iconName,tempModel.name,tempModel.friendState];
                        NSString *conditionStr = [NSString stringWithFormat:@"targetId = %@",tempModel.targetId];
                        BOOL success = [[YZDBManager sharedManage] updateData:setStr table:kNewFriendTable andCondition:conditionStr];
                        if (success) {}
                    }
                }
            }
            
            // 更新是否有新朋友申请的状态
            self->_haveLatestFriend = YES;
            
        } @catch(NSException *exception) {
            
        }
    } completed:^{
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.friendList reloadData];
        });
    }];
}


- (BOOL)insertNewFriend:(YZFriendModel *)friendModel {
    
    BOOL success = [[YZDBManager sharedManage] insertNewFriendData:friendModel tableName:kNewFriendTable];
    if (success) {
        //        [SVProgressHUD showSuccessWithStatus:@"处理成功"];
    }
    
    return success;
}

#pragma mark - 刷新好友列表
- (void)refreshFriendList:(NSNotification *)notify {
    NSDictionary *nofiDic = notify.object;
    self.lastestModel = (YZFriendModel *)(nofiDic[@"lastModel"]);
    self.lastestModelArr = nofiDic[@"lastModelArr"];
    
    // 根据targetId请求用户头像，名字。
    NSString *userId = self.lastestModel.targetId;
    [self queryUserInfo:userId controller:self];
}

#pragma mark - private
- (void)saveAcceptMessageList:(YZMessageListModel *)model {
    [[YZDBManager sharedManage] insertMessageListData:model tableName:kChatMessageListTable];
}

- (void)updateAcceptMessageList:(YZMessageListModel *)model {
    NSString *setStr = [NSString stringWithFormat:@"lastContent = '%@' , redHotNum = '%@', avatar = '%@' ,nickName = '%@'",model.message,model.redHotNumber,model.imageName,model.name];
    NSString *condition = [NSString stringWithFormat:@"showUserid = '%@'",model.showUserId];
    
    BOOL updateRet = [[YZDBManager sharedManage] updateData:setStr table:kChatMessageListTable andCondition:condition];
    if (updateRet) {
        NSLog(@"更新消息列表成功");
    }
    
}

- (void)updateMessageListRedDotNumber:(YZMessageListModel *)model {
    NSString *setStr = [NSString stringWithFormat:@"redHotNum = 0"];
    NSString *condition = [NSString stringWithFormat:@"showUserid = '%@'",model.showUserId];
    
    BOOL updateRet = [[YZDBManager sharedManage] updateData:setStr table:kChatMessageListTable andCondition:condition];
    if (updateRet) {
        NSLog(@"更新消息红点数量成功");
    }
}

#pragma mark - 接收刷新通知
// 刷新消息列表
- (void)refreshMessageListTable:(NSNotification *)notify {
    YZMessageListModel *model = (notify.object);
    
    // 查询用户信息
    [self queryUserInfo:model];
}

#pragma mark - 接收ShowTabRedDotNotification通知
- (void)showTabDot:(NSNotification *)notify {
    NSUInteger obj = [(NSNumber *)notify.object integerValue];
    UIButton *messageListBtn = (UIButton *)[self.tapScrollView viewWithTag:1000];
    UIButton *friendListBtn = (UIButton *)[self.tapScrollView viewWithTag:1001];
    
    if (obj == 0){
        dispatch_async(dispatch_get_main_queue(), ^{
            [messageListBtn setBadge:^(BadgeBuilder *builder) {
                builder.number = @0;
            }];
        });
    } else if (obj == 1) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [friendListBtn setBadge:^(BadgeBuilder *builder) {
                builder.number = @0;
            }];
        });
    }
}

#pragma mark - back
- (void)onBack:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int index =  scrollView.contentOffset.x / scrollView.frame.size.width;
    
    NSLog(@"index--->%d", index);
    if (0 == index) {
        
        [UIView animateWithDuration:0.2 animations:^{
            self.tapScrollView.indicatorView.frame = CGRectMake(0, 0, self.tapScrollView.indicatorScrollView.frame.size.width/2, 5);
        }];
    } else if (1 == index) {
        
        [UIView animateWithDuration:0.2 animations:^{
            self.tapScrollView.indicatorView.frame = CGRectMake(self.tapScrollView.indicatorScrollView.bounds.size.width / 2, 0, self.tapScrollView.indicatorScrollView.frame.size.width/2, 5);
        }];
    }
}

#pragma mark - register cell
- (void)registerCell {
    [self.friendList registerClass:[YZFriendListCell1 class] forCellReuseIdentifier:flagCell1];
    [self.friendList registerClass:[YZFriendListCell2 class] forCellReuseIdentifier:flagCell2];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
